package com.second.app.superthread;


import java.util.concurrent.CountDownLatch;

/**
 * @Author GYZ
 * @Date 2024/1/22
 * <pre>
 *
 * </pre>
 */

class Thread110 extends Thread {

    private final CountDownLatch comingTag; //裁判等待所有运动员到来

    private final CountDownLatch waitTag; //等待裁判说准备开始

    private final CountDownLatch waitRunTag; //等待起跑

    private final CountDownLatch beginTag; //起跑

    private final CountDownLatch endTag;// 所有运动员到达终点


    public Thread110(CountDownLatch comingTag,
                     CountDownLatch waitTag,
                     CountDownLatch waitRunTag,
                     CountDownLatch beginTag,
                     CountDownLatch endTag) {
        this.comingTag = comingTag;
        this.waitTag = waitTag;
        this.waitRunTag = waitRunTag;
        this.beginTag = beginTag;
        this.endTag = endTag;
    }

    @Override
    public void run() {
        try {
            System.out.println("运动员使用不同交通工具不同速度到达起点，正向这头走！");
            Thread.sleep((int) (Math.random() * 10000));
            System.out.println(Thread.currentThread().getName() + "到起跑点了！");
            comingTag.countDown();
            System.out.println("等待裁判说准备！");
            waitTag.await();
            System.out.println("各就各位！准备起跑姿势！");
            Thread.sleep((int) (Math.random() * 10000));
            waitRunTag.countDown();
            beginTag.await();
            System.out.println(Thread.currentThread().getName() + " 运动员起跑 并且跑步用时不确定");
            Thread.sleep((int) (Math.random() * 10000));
            endTag.countDown();
            System.out.println(Thread.currentThread().getName() + " 运动员到达终点");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class TheWholeExample {

    public static void main(String[] args) {
        CountDownLatch comingTag = new CountDownLatch(10);
        CountDownLatch waitTag = new CountDownLatch(1);
        CountDownLatch waitRunTag = new CountDownLatch(10);
        CountDownLatch beginTag = new CountDownLatch(1);
        CountDownLatch endTag = new CountDownLatch(10);

        Thread110[] thread110s = new Thread110[10];

        for (int i = 0; i < thread110s.length; i++) {
            thread110s[i] = new Thread110(comingTag, waitTag, waitRunTag, beginTag, endTag);
            thread110s[i].start();
        }
        try {
            System.out.println("裁判等待所有选手的到来！");
            comingTag.await();
            System.out.println("裁判看所有运动员来了，各就各位前 巡视5s");
            Thread.sleep(5000);
            waitTag.countDown();
            System.out.println("各就各位！");
            waitRunTag.await();
            Thread.sleep(2000);
            System.out.println("发令枪响起！");
            beginTag.countDown();
            endTag.await();
            System.out.println("所有运动员到达，统计比赛名次！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
